<?php

namespace App\Actions\Web;

use App\Models\User;
use App\Models\UserLoginLog;
use Illuminate\Database\Eloquent\Model;

class UserLogAction
{

    protected $data;
    protected $type;
    protected $model;
    protected $user;
    protected $description = '';
    protected $detail=[];

    /**
     * Undocumented function
     *
     * @param Model|null $model
     */
    public function __construct(Model $model = null, $user=null)
    {
        $this->model = $model;
        $this->user = $user;
    }

    /**
     * 手动设置操作人员
     *
     * @param AdminUser $admin_user
     * @return $this
     */
    public function user(User $user)
    {
        $this->user = $user;
        return $this;
    }

    /**
     * 登录日志
     * @return $this
     */
    public function login()
    {
        $this->type = UserLoginLog::TYPE1;
        $this->description = ['登录成功'];
        return $this;
    }

    public function register()
    {
        $this->type = UserLoginLog::TYPE_REGISTER;
        $this->description = ['注册'];
        return $this;
    }

    /**
     * 设置类型
     *
     * @param string $type
     * @return $this
     */
    public function type($type = UserLoginLog::TYPE_OTHER)
    {
        $this->type = $type;
        return $this;
    }

    /**
     * 设置描述文字
     *
     * @param string|array $description
     * @return $this
     */
    public function description($description = '')
    {
        $this->description = $description;
        return $this;
    }

    /**
     * 插入新日志
     *
     */
    public function log()
    {
        try {
            UserLoginLog::create([
                'gid' => $this->user ? $this->user->gid : '',
                'name' => $this->user ? $this->user->name : '',
                'zjhm'    => $this->user ? $this->user->zjhm : '',
                'method'  => request()->method(),
                'ip'      => getIp(),
                'input'   => json_encode(request()->input()),
                'description' => $this->description,
                'relation_table' => $this->model ? $this->model->getTable() : '',
                'relation_id' => $this->model ? ($this->model->id ?: 0) : 0,
                'type' => $this->type ?: UserLoginLog::TYPE_OTHER,
            ]);
        } catch (\Throwable $th) {
        }
    }


    /**
     * Create a form instance.
     *
     * @param  mixed  ...$params
     * @return $this
     */
    public static function make(...$params)
    {
        return new static(...$params);
    }

    
}